package com.le.tester.webpage.lock;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：使用ReentrantLock加上较轻量级别的锁,有尝试的机制
 * 最多等待一秒，如果一秒后仍然未获取到锁，那么tryLock就会返回false,并且做一些额外的处理，并不会无限的等待下去
 * 所以使用ree必比syn更加的安全，tryLock的时候不会导致死锁
 */
public class CounterRee {
    private final Lock lock = new ReentrantLock();
    private int count;

    private void add(int i) {
        lock.lock();
        try {
            count += i;
        } finally {
            lock.unlock();
        }
    }
}

//condition来可以实现syn中的wait和notify功能的
class TaskQueue {
    private final Lock lock = new ReentrantLock();
    //拿到锁的newCondition
    private final Condition condition = lock.newCondition();
    //link链表
    private Queue<String> queue = new LinkedList<>();

    public void addTask(String s) {
        lock.lock();
        try {
            queue.add(s);
            //可以类比syn中的notifyAll
            //不过这个是随机的唤醒一个阻塞的线程
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public String getTask() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                //可以类比syn中的wait
                condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return queue.remove();
    }
}
